<?php

class PartsController extends CController
{
        public $breadcrumbs;
	/**
	 * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
	 * using two-column layout. See 'protected/views/layouts/column2.php'.
	 */
	public $layout='main'; 

	/**
	 * @return array action filters
	 */
	public function filters() 
	{
		return array(
			'accessControl', // perform access control for CRUD operations
		);
	}

	/**
	 * Specifies the access control rules.
	 * This method is used by the 'accessControl' filter.
	 * @return array access control rules
	 */
	public function accessRules()
	{
		return array(
			array('allow',  // allow all users to perform 'index' and 'view' actions
				'actions'=>array('index','view'),
				'users'=>array('*'),
			),
			array('allow', // allow authenticated user to perform 'create' and 'update' actions
				'actions'=>array('create','update','GeneratePdf','GenerateExcel','getSubcategories','getSection','getProcess'),
				'users'=>array('*'),
			),
			array('allow', // allow admin user to perform 'admin' and 'delete' actions
				'actions'=>array('admin','delete'),
				'users'=>array('*'),
			),
			array('deny',  // deny all users
				'users'=>array('*'),
			),
		);
	}

	/**
	 * Displays a particular model.
	 * @param integer $id the ID of the model to be displayed
	 */
	public function actionView($id)
	{
		$this->render('view',array(
			'model'=>$this->loadModel($id),
		));
	}
	
	public function actionGetSubcategories()
	{
		$id_categories = $_POST['id_categories'];
		$subCategories = ItemSubcategories::model()->findAll("id_category='$id_categories'");
		
		foreach ($subCategories as $subCategorie):
    		$data[$subCategorie->id] = $subCategorie->id . ' - ' . $subCategorie->name;   
		endforeach;	
		if($data != null){
	   		echo CHtml::tag('option',array('value'=>""),CHtml::encode("Kode - SubCategory"),true);
	   		foreach($data as $value=>$name)
		   {
				echo CHtml::tag('option',array('value'=>$value),CHtml::encode($name),true);
		   }
	    }else{
	   		echo CHtml::tag('option',array('value'=>''),CHtml::encode('Subcategory Belum Tersedia'),true);
	    } 
	}
	
	public function actionGetSection()
	{
		$id_subcategories = $_POST['id_subcategories'];
		$sections = ItemSection::model()->findAll("id_sub_category='$id_subcategories'");
		
		foreach ($sections as $section):
    		$data[$section->id] = $section->id . ' - ' . $section->name;   
		endforeach;	
		if($data != null){
	   		echo CHtml::tag('option',array('value'=>""),CHtml::encode("Kode - section"),true);
	   		foreach($data as $value=>$name)
		   {
				echo CHtml::tag('option',array('value'=>$value),CHtml::encode($name),true);
		   }
	   }else{
	   		echo CHtml::tag('option',array('value'=>''),CHtml::encode('section Belum Tersedia'),true);
	   } 
	}
	
	public function actionGetProcess()
	{
		$id_section = $_POST['id_section'];
		$process = ItemProcess::model()->findAll("id_section='$id_section'");
		
		foreach ($process as $data_process):
    		$data[$data_process->id] = $data_process->id . ' - ' . $data_process->name;   
		endforeach;	
		if($data != null){
	   		echo CHtml::tag('option',array('value'=>""),CHtml::encode("Kode - Process"),true);
	   		foreach($data as $value=>$name)
		   {
				echo CHtml::tag('option',array('value'=>$value),CHtml::encode($name),true);
		   }
	   }else{
	   		echo CHtml::tag('option',array('value'=>''),CHtml::encode('Process Belum Tersedia'),true);
	   } 
	}

	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */
	public function actionCreate()
	{
		$model=new Parts;

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Parts']))
		{
			$model->attributes=$_POST['Parts'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('create',array(
			'model'=>$model,
		));
	}

	/**
	 * Updates a particular model.
	 * If update is successful, the browser will be redirected to the 'view' page.
	 * @param integer $id the ID of the model to be updated
	 */
	public function actionUpdate($id)
	{
		$model=$this->loadModel($id);

		// Uncomment the following line if AJAX validation is needed
		// $this->performAjaxValidation($model);

		if(isset($_POST['Parts']))
		{
			$model->attributes=$_POST['Parts'];
			if($model->save())
				$this->redirect(array('view','id'=>$model->id));
		}

		$this->render('update',array(
			'model'=>$model,
		));
	}

	/**
	 * Deletes a particular model.
	 * If deletion is successful, the browser will be redirected to the 'admin' page.
	 * @param integer $id the ID of the model to be deleted
	 */
	public function actionDelete($id)
	{
		if(Yii::app()->request->isPostRequest)
		{
			// we only allow deletion via POST request
			$this->loadModel($id)->delete();

			// if AJAX request (triggered by deletion via admin grid view), we should not redirect the browser
			if(!isset($_GET['ajax']))
				$this->redirect(isset($_POST['returnUrl']) ? $_POST['returnUrl'] : array('admin'));
		}
		else
			throw new CHttpException(400,'Invalid request. Please do not repeat this request again.');
	}

	/**
	 * Lists all models.
	 */
	public function actionIndex()
	{
            $session=new CHttpSession;
            $session->open();		
            $criteria = new CDbCriteria();            

                $model=new Parts('search');
                $model->unsetAttributes();  // clear any default values

                if(isset($_GET['Parts']))
		{
                        $model->attributes=$_GET['Parts'];
			
			
                   	
                       if (!empty($model->id)) $criteria->addCondition('id = "'.$model->id.'"');
                     
                    	
                       if (!empty($model->part_code)) $criteria->addCondition('part_code = "'.$model->part_code.'"');
                     
                    	
                       if (!empty($model->name)) $criteria->addCondition('name = "'.$model->name.'"');
                     
                    	
                       if (!empty($model->lead_time_days)) $criteria->addCondition('lead_time_days = "'.$model->lead_time_days.'"');
                     
                    	
                       if (!empty($model->unit_code)) $criteria->addCondition('unit_code = "'.$model->unit_code.'"');
                     
                    	
                       if (!empty($model->description)) $criteria->addCondition('description = "'.$model->description.'"');
                     
                    	
                       if (!empty($model->id_categories)) $criteria->addCondition('id_categories = "'.$model->id_categories.'"');
                     
                    	
                       if (!empty($model->id_subcategories)) $criteria->addCondition('id_subcategories = "'.$model->id_subcategories.'"');
                     
                    	
                       if (!empty($model->id_section)) $criteria->addCondition('id_section = "'.$model->id_section.'"');
                     
                    	
                       if (!empty($model->id_process)) $criteria->addCondition('id_process = "'.$model->id_process.'"');
                     
                    	
                       if (!empty($model->id_status)) $criteria->addCondition('id_status = "'.$model->id_status.'"');
                     
                    	
                       if (!empty($model->item_id)) $criteria->addCondition('item_id = "'.$model->item_id.'"');
                     
                    	
                       if (!empty($model->status_part)) $criteria->addCondition('status_part = "'.$model->status_part.'"');
                     
                    	
                       if (!empty($model->supplier_code)) $criteria->addCondition('supplier_code = "'.$model->supplier_code.'"');
                     
                    	
                       if (!empty($model->part_maker)) $criteria->addCondition('part_maker = "'.$model->part_maker.'"');
                     
                    	
                       if (!empty($model->min_order_qty)) $criteria->addCondition('min_order_qty = "'.$model->min_order_qty.'"');
                     
                    	
                       if (!empty($model->re_order_level)) $criteria->addCondition('re_order_level = "'.$model->re_order_level.'"');
                     
                    	
                       if (!empty($model->unit_of_measure)) $criteria->addCondition('unit_of_measure = "'.$model->unit_of_measure.'"');
                     
                    	
                       if (!empty($model->section_name)) $criteria->addCondition('section_name = "'.$model->section_name.'"');
                     
                    	
                       if (!empty($model->price)) $criteria->addCondition('price = "'.$model->price.'"');
                     
                    	
                       if (!empty($model->currency)) $criteria->addCondition('currency = "'.$model->currency.'"');
                     
                    	
                       if (!empty($model->current_stock)) $criteria->addCondition('current_stock = "'.$model->current_stock.'"');
                     
                    	
                       if (!empty($model->status_po)) $criteria->addCondition('status_po = "'.$model->status_po.'"');
                     
                    	
                       if (!empty($model->part)) $criteria->addCondition('part = "'.$model->part.'"');
                     
                    	
                       if (!empty($model->item_code)) $criteria->addCondition('item_code = "'.$model->item_code.'"');
                     
                    	
                       if (!empty($model->actual_qty)) $criteria->addCondition('actual_qty = "'.$model->actual_qty.'"');
                     
                    	
                       if (!empty($model->status_stock)) $criteria->addCondition('status_stock = "'.$model->status_stock.'"');
                     
                    	
                       if (!empty($model->max_stock)) $criteria->addCondition('max_stock = "'.$model->max_stock.'"');
                     
                    	
                       if (!empty($model->min_stock)) $criteria->addCondition('min_stock = "'.$model->min_stock.'"');
                     
                    	
                       if (!empty($model->stock_taking)) $criteria->addCondition('stock_taking = "'.$model->stock_taking.'"');
                     
                    	
                       if (!empty($model->mrp)) $criteria->addCondition('mrp = "'.$model->mrp.'"');
                     
                    	
                       if (!empty($model->jumlah)) $criteria->addCondition('jumlah = "'.$model->jumlah.'"');
                     
                    	
                       if (!empty($model->currency_code)) $criteria->addCondition('currency_code = "'.$model->currency_code.'"');
                     
                    	
                       if (!empty($model->inspection_received)) $criteria->addCondition('inspection_received = "'.$model->inspection_received.'"');
                     
                    	
                       if (!empty($model->inspection_rejected)) $criteria->addCondition('inspection_rejected = "'.$model->inspection_rejected.'"');
                     
                    	
                       if (!empty($model->is_new_item)) $criteria->addCondition('is_new_item = "'.$model->is_new_item.'"');
                     
                    	
                       if (!empty($model->link_part_code)) $criteria->addCondition('link_part_code = "'.$model->link_part_code.'"');
                     
                    	
                       if (!empty($model->part_kind)) $criteria->addCondition('part_kind = "'.$model->part_kind.'"');
                     
                    			
		}
                 $session['Parts_records']=Parts::model()->findAll($criteria); 
       

                $this->render('index',array(
			'model'=>$model,
		));

	}

	/**
	 * Manages all models.
	 */
	public function actionAdmin()
	{
		$model=new Parts('search');
		$model->unsetAttributes();  // clear any default values
		if(isset($_GET['Parts']))
			$model->attributes=$_GET['Parts'];

		$this->render('admin',array(
			'model'=>$model,
		));
	}

	/**
	 * Returns the data model based on the primary key given in the GET variable.
	 * If the data model is not found, an HTTP exception will be raised.
	 * @param integer the ID of the model to be loaded
	 */
	public function loadModel($id)
	{
		$model=Parts::model()->findByPk($id);
		if($model===null)
			throw new CHttpException(404,'The requested page does not exist.');
		return $model;
	}

	/**
	 * Performs the AJAX validation.
	 * @param CModel the model to be validated
	 */
	protected function performAjaxValidation($model)
	{
		if(isset($_POST['ajax']) && $_POST['ajax']==='parts-form')
		{
			echo CActiveForm::validate($model);
			Yii::app()->end();
		}
	}
        public function actionGenerateExcel()
	{
            $session=new CHttpSession;
            $session->open();		
            
             if(isset($session['Parts_records']))
               {
                $model=$session['Parts_records'];
               }
               else
                 $model = Parts::model()->findAll();

		
		Yii::app()->request->sendFile(date('YmdHis').'.xls',
			$this->renderPartial('excelReport', array(
				'model'=>$model
			), true)
		);
	}
        public function actionGeneratePdf() 
	{
           $session=new CHttpSession;
           $session->open();
		Yii::import('application.modules.admin.extensions.giiplus.bootstrap.*');
		require_once('tcpdf/tcpdf.php');
		require_once('tcpdf/config/lang/eng.php');

             if(isset($session['Parts_records']))
               {
                $model=$session['Parts_records'];
               }
               else
                 $model = Parts::model()->findAll();



		$html = $this->renderPartial('expenseGridtoReport', array(
			'model'=>$model
		), true);
		
		//die($html);
		
		$pdf = new TCPDF();
		$pdf->SetCreator(PDF_CREATOR);
		$pdf->SetAuthor(Yii::app()->name);
		$pdf->SetTitle('Parts Report');
		$pdf->SetSubject('Parts Report');
		//$pdf->SetKeywords('example, text, report');
		$pdf->SetHeaderData('', 0, "Report", '');
		$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, "Example Report by ".Yii::app()->name, "");
		$pdf->setHeaderFont(Array('helvetica', '', 8));
		$pdf->setFooterFont(Array('helvetica', '', 6));
		$pdf->SetMargins(15, 18, 15);
		$pdf->SetHeaderMargin(5);
		$pdf->SetFooterMargin(10);
		$pdf->SetAutoPageBreak(TRUE, 0);
		$pdf->SetFont('dejavusans', '', 7);
		$pdf->AddPage();
		$pdf->writeHTML($html, true, false, true, false, '');
		$pdf->LastPage();
		$pdf->Output("Parts_002.pdf", "I");
	}
}
